import type { Module, ActionContext } from 'vuex'
import type { AxiosResponse } from 'axios'
import type { reportStateType } from './typings'
import { deviceListPageGet, deviceListPageInfoGet, communicationExport } from '~/api/monitor/report'
import { DownloadAttachment } from '~/utils/util'

const report: Module<reportStateType, reportStateType> = {
  namespaced: true,
  state: {},
  getters: {},
  mutations: {},
  actions: {
    //  通讯数据-列表
    DeviceListPageGet<S, T>(_: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        deviceListPageGet<T>(params)
          .then((res: AxiosResponse) => {
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    },
    //  通讯数据-列表-详情
    DeviceListPageInfoGet<S, T>(_: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        deviceListPageInfoGet<T>(params)
          .then((res: AxiosResponse) => {
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    },
    // 通讯数据-导出
    async CommunicationExport<S, T>(_: ActionContext<S, T>, params: T) {
      return await communicationExport<T>(params).then((res: AxiosResponse) => {
        const contentDisposition = res?.headers?.['content-disposition']
        if (contentDisposition && res.data) {
          DownloadAttachment(decodeURI(contentDisposition.substring(20)), res.data)
        }
        return res.data
      })
    }
  }
}

export default report
